<template>
  <div class="login-container">
    <!-- 登录 -->
    <div class="login-content">
      <!-- 左边 -->
      <div class="left">
        <el-form ref="formRef" :model="loginForm" :rules="loginRules" class="login-form" auto-complete="on" label-position="left">
          <div class="title-container">
            <h3 class="title-h3">智能视觉工厂物联系统</h3>
            <p class="title-p">Intelligent Vision Factory IOT System</p>
          </div>
          <!-- 账号 -->
          <p class="label">账号</p>
          <el-form-item prop="AccountName">
            <el-input ref="AccountName" v-model="loginForm.AccountName" placeholder="请输入账号名称" name="AccountName" type="text" tabindex="1" auto-complete="on" clearable="true" :class="{
              'inputDefault': true, 'half-border': ishalfBorder, 'orange-border': isorangeBorder
            }" @mousemove="ishalfBorder = true" @mouseout="ishalfBorder = false" @focus="isorangeBorder = true" @blur="isorangeBorder = false" />
          </el-form-item>
          <!-- 密码 -->
          <p class="label">密码</p>
          <el-form-item prop="AccountPwd" class="password">
            <el-input class="passwordInput" :key="passwordType" show-password type="password" ref="passwordRef" v-model="loginForm.AccountPwd" placeholder="请输入账号密码" clearable="true"
              @keyup.enter="handleLogin" :class="{
                'inputDefault': true, 'half-border': ishalf2Border, 'orange-border': isorange2Border
              }" @mousemove="ishalf2Border = true" @mouseout="ishalf2Border = false" @focus="isorange2Border = true" @blur="isorange2Border = false" />

          </el-form-item>
          <!-- 记住密码 -->
          <!-- <el-checkbox v-if="!desc" v-model="checked" class="remeberPwd" label="记住密码"></el-checkbox> -->
          <p class="desctext">{{ desc }}</p>
          <!-- 登录按钮 -->
          <el-button :loading="loading" type="warning" class="loginbtn" @keyup.enter="handleLogin" @click.prevent="handleLogin">登 录</el-button>
        </el-form>
      </div>
      <!-- 右边 logo-->
      <div class="right">
        <img src="../../assets/login-bg.png" alt="" class="right-img" />
      </div>
    </div>
    <!-- 版权 -->
    <p class="copyright">©2023 北京先见科技有限公司 版权所有</p>
  </div>
</template>



<script lang="ts" setup>
//用户登录相关的小仓库
import { useUserInfoStore } from "@/stores/userInfo";
import type { FormInstance } from "element-plus";
import { computed, nextTick, ref, watch, onMounted } from "vue";

import { Base64 } from 'js-base64'
import { useRoute, useRouter } from "vue-router";
onMounted(() => {
  if (localStorage.getItem('checkedAttr') == 'true') {
     loginForm.value.AccountName = Base64.decode(localStorage.getItem('checkedName'))
      loginForm.value.AccountPwd = Base64.decode(localStorage.getItem('checkedPass'))
  }
  

  checked.value = JSON.parse(localStorage.getItem('checkedAttr'))


  // loginForm.value.AccountName = localStorage.getItem('checkedName')
  // } else {
  // console.log(999);
  // 
  // checked.value = false
  // }
  // if (checked.value) {
  //   localStorage.setItem('checkedName', JSON.stringify(Base64.encode(loginForm.value.AccountName)))
  //   localStorage.setItem('checkedPass', JSON.stringify(Base64.encode(loginForm.value.AccountPwd)))
  // } else {
  //   localStorage.removeItem('checkedName')
  //   localStorage.removeItem('checkedPass')
  // }
  // if (localStorage.getItem('checkedName') && localStorage.getItem('checkedPwd')) {
  //   loginForm.value.AccountName = localStorage.getItem('checkedName')
  //   loginForm.value.AccountPwd = localStorage.getItem('checkedPwd')
  //   checked.value = true
  // }

})
//获取用户小仓库
const userInfoStore = useUserInfoStore();
//获取路由对象
const route = useRoute();
//获取路由器对象
const router = useRouter();
//获取el-form组件实例的VC,调用validate方法确保校验通过
const formRef = ref<FormInstance>();
//控制按钮的加载效果:默认没有
const loading = ref(false);
//获取密码的组件实例
const passwordRef = ref<HTMLInputElement>();
//收集登录页面:账号与密码的响应式数据
const loginForm = ref<any>({
  AccountName: "",
  AccountPwd: "",
});
const checked = ref<any>(false);
//密码的文本框类型:默认密码类型带小点点 
const passwordType = ref("password");
const desc = ref('')
const ishalfBorder = ref(false)
const isorangeBorder = ref(false)
const ishalf2Border = ref(false)
const isorange2Border = ref(false)
// 正则校验
const usernameRegx = /^[a-zA-Z]{1}([a-zA-Z0-9]){4,15}$/
const passwordRegx = /^[a-zA-Z]{1}(.){7,31}$/

//点击密码后面小眼睛:切换密码表单类型,小眼睛来回切换
/* 
切换密码的显示/隐藏
*/
// const showPwd = () => {
//   //无非passwrodType来回切换
//   passwordType.value = passwordType.value === "password" ? "text" : "password";
//   //nextTick:当响应式数据发生变化的时候,获取更新后DOM
//   nextTick(() => {
//     //密码表单元素聚焦
//     passwordRef.value?.focus();
//   });
// };



//存储login登录query参数
const redirect = ref("");

//自定义校验规则:用户名字规则---->只要文本发生变化就会触发次函数
const validateUsername = (rule: any, value: any, callback: any) => {
  if (value) {
    if (usernameRegx.test(value)) {
      callback();
    } else {
      callback(new Error("账号名称必须由英文或数字组成，且必须英文字母开头，范围在 5-16 个内"));
    }
  } else {
    callback(new Error(""));
  }

};
//自定义校验规则:密码的规则
const validatePassword = (rule: any, value: any, callback: any) => {
  if (value) {
    if (passwordRegx.test(value)) {
      callback();
    } else {
      callback(new Error("账号密码必须由英文、数字、标点符号组成，且必须英文字母开头，范围在 8-32 个内。"));
    }
  } else {
    callback(new Error(""));
  }

};

//表单元素校验规则
const loginRules = {
  //校验用户名:required,必须校验字段  validator:自定义校验规则
  AccountName: [
    { required: true, validator: validateUsername, trigger: "change" },
  ],
  //校验密码:trigger,触发校验时机
  AccountPwd: [
    { required: true, validator: validatePassword, trigger: "change" },
  ],
};

//监听路由对象(上来立即监听一次)
watch(
  route,
  () => {
    //判断是否有query参数,如果有query参数。把他赋值给rediret这个ref对象
    redirect.value = route.query && (route.query.redirect as string);
  },
  { immediate: true }
);



watch(
  () => loginForm.value.AccountName,
  (value) => {
    console.log(value);

    value == '' && formRef.value?.clearValidate();
  },
  { deep: true }
);


/* 
点击登陆的回调
*/
const handleLogin = async () => {
  //点击登录按钮,看表单元素每一项目是否校验通过
  await formRef.value?.validate();

  //按钮加载效果开始动
  //登录需要的账号与密码的参数
  const { AccountName, AccountPwd } = loginForm.value;
  //后台项目:pinia->获取小仓局,调用它的actions的方法,去发请求
  try {
    //调用用户相关的小仓库login方法->进行登录请求
    await userInfoStore.login(AccountName, AccountPwd);
if(checked.value==true){
  localStorage.setItem('checkedName', JSON.stringify(Base64.encode(loginForm.value.AccountName)))
    localStorage.setItem('checkedPass', JSON.stringify(Base64.encode(loginForm.value.AccountPwd)))
}
    router.push("/home");
  } finally {

    const descinforef: any = ref(computed(() => userInfoStore.$state.desc));
    const descinfo = ref<any>(descinforef);
    desc.value = descinfo.value
    setTimeout(() => {
      // 修改仓库的值为空
      userInfoStore.desc = ''
      descinfo.value = ''
      desc.value = ''
    }, 3000)
    //登录成功、还是失败,小加载消失
  }
};
watch(
  () => checked.value,
  (value) => {
   checked.value = value
   localStorage.setItem('checkedAttr', checked.value)
     if (value== true) {
    localStorage.setItem('checkedName', JSON.stringify(Base64.encode(loginForm.value.AccountName)))
    localStorage.setItem('checkedPass', JSON.stringify(Base64.encode(loginForm.value.AccountPwd)))
  } else {
    localStorage.removeItem('checkedName')
    localStorage.removeItem('checkedPass')
  }
  },
  { deep: true }
)
// watch(() => checked.value, () => {
//   // checked.value = localStorage.getItem('checkedAttr')
//   if (localStorage.getItem('checkedAttr')) {
//     console.log(localStorage.getItem('checkedAttr'));
    
//     localStorage.setItem('checkedAttr', localStorage.getItem('checkedAttr'))
//   } else {
//     localStorage.setItem('checkedAttr', checked.value)
//     checked.value = JSON.parse(localStorage.getItem('checkedAttr'))
//   }

//   if (checked.value == true) {
//     localStorage.setItem('checkedName', JSON.stringify(Base64.encode(loginForm.value.AccountName)))
//     localStorage.setItem('checkedPass', JSON.stringify(Base64.encode(loginForm.value.AccountPwd)))
//   } else {
//     localStorage.removeItem('checkedName')
//     localStorage.removeItem('checkedPass')
//   }
// },
//   { deep: true }
// )

</script>

<style lang="scss" scoped>
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg: #283443;
$light_gray: #fff;
$cursor: #fbfbfb;



//主要是解决光标颜色和文字颜色一致
//caret-color属性可以改变输入框插入光标的颜色，同时又不改变输入框里面的内容的颜色。
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  box-shadow: 0px 0px 0.8356px 0px rgba(9, 30, 66, 0.31), 0px 15.04075px 23.39672px 0px rgba(9, 30, 66, 0.15);

  /* reset element-ui css */
  .login-content {
    display: flex;
    height: 480px;
    width: 960px;
    border-radius: 24px;
    box-shadow: 0px 0px 0.8356px 0px rgba(9, 30, 66, 0.31), 0px 15.04075px 23.39672px 0px rgba(9, 30, 66, 0.15);

    .left {
      width: 480px;
      padding: 40px;
      background: #ffffff;
      border-top-left-radius: 15px;
      border-bottom-left-radius: 15px;

      .login-form {
        position: relative;
        width: 400px;
        max-width: 100%;
        margin: 0 auto;
        overflow: hidden;

        .title-container {
          position: relative;
          /*浏览器中文字不能被选中*/
          -moz-user-select: none;
          -webkit-user-select: none;
          -ms-user-select: none;
          user-select: none;

          .title-h3 {
            font-weight: 500;
            font-size: 40px;
            line-height: 60px;
            color: #262626;
            margin-bottom: -6px;
          }

          .title-p {
            text-align: center;
            font-size: 18.5px !important;
            line-height: 28px;
            color: #8c8c8c;
            font-weight: 400 !important;
            -webkit-font-smoothing: antialiased;
            text-transform: uppercase;
            margin-bottom: 20px;
          }
        }

        .label {
          font-size: 14px;
          line-height: 20px;
          color: rgba(89, 89, 89, 1);
          font-weight: 500;
          padding: 10px 0;
          /*浏览器中文字不能被选中*/
          -moz-user-select: none;
          -webkit-user-select: none;
          -ms-user-select: none;
          user-select: none;


        }

        .inputDefault {
          border: 1px solid #E6E6E6;
          border-radius: 8px;
        }

        .half-border {
          border: $mouse-hover-border;
          border-radius: 8px;
        }

        .orange-border {
          border: $mouse-downOrFocus-border;
          border-radius: 8px;
        }

        .password {
          .passwordInput {
            position: relative;
          }

          .show-pwd {
            position: absolute;
            left: 370px;
          }
        }

        .desctext {
          position: absolute;
          font-size: 14px;
          color: #d45a5a;
        }
.remeberPwd{
  position: absolute;

}


        .loginbtn {
          font-family: 'Source Han Sans CN';
          width: 100%;
          /*margin-top: 35px;*/
          margin-top: 50px;
          height: 48px;
          font-size: 14px;
          background-color: #F2994A;
          border-radius: 6px;
          box-shadow: 0px 8px 16px 0px rgba(242, 153, 74, 0.25), 0px 0px 8px 0px rgba(242, 153, 74, 0.05);
        }

        .el-form-item {
          background: #FFF;
          border-radius: 8px;
          color: #454545;
          width: 400px;

          /*.svg-container {
              padding-left: 15px;
              padding-top: 5px;
            }*/

          .el-input {
            display: inline-block;
            height: 48px;
            width: 100%;

            .el-input__wrapper {
              width: 100%;
              height: 100%;
              background-color: transparent;
              box-shadow: none;
              height: 48px;

              input {
                background: transparent;
                width: 400px;
                -webkit-appearance: none;
                border-radius: 0px;
                padding: 12px 5px 12px 15px;
                color: $cursor;
                height: 47px;
                caret-color: $cursor;

                &:-webkit-autofill {
                  box-shadow: 0 0 0px 1000px $bg inset !important;
                  -webkit-text-fill-color: $cursor !important;
                }
              }
            }
          }
        }
      }
    }

    .right {
      height: 100%;
      background: #35364b;
      border-top-right-radius: 15px;
      border-bottom-right-radius: 15px;

      .right-img {
        -webkit-user-drag: none;
      }
    }
  }

  .copyright {
    text-align: center;
    color: #595959;
    font-weight: 500;
    font-size: 16px;
    line-height: 24px;
    position: absolute;
    bottom: 24px;
  }
}

:deep(.el-input__wrapper) {
  width: 100%;
  height: 100%;
  background-color: transparent;
  box-shadow: none;
  height: 48px;
  margin: auto auto;
}



/*深度修改校验错误以后的提示*/
:deep(.el-form-item__error) {
  top: 50px;
  color: #F2994A;
  font-size: 12px;
  font-style: normal;
  font-weight: 400;
  line-height: 20px;
}



:deep(input:-internal-autofill-selected) {
  background-color: red;
}

:deep(.el-form-item.is-error .el-input__wrapper) {
  box-shadow: none;
}

:deep(.el-button) {
  --el-button-hover-text-color: #ffffff;
}
/*当记住密码被勾选的时候，记住密码的文字颜色变色*/
:deep(.el-checkbox__input.is-checked+.el-checkbox__label){
  color:#F2994A;
}
:deep(.el-checkbox__inner:hover){
  border: 1px solid #F2994A;
}
/*当记住密码被勾选的时候，记住密码的框变色*/
:deep(.el-checkbox__input.is-checked .el-checkbox__inner){
  background: #F2994A;
}

:deep(.el-checkbox){
  --el-checkbox-checked-input-border-color:#F2994A;
}
</style>


